package com.bml.architect.sentinel.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: baiml
 * @Title: SentenelController
 * @ProjectName: 中台技术平台
 * @Depart 中台研发部
 * @Description:  原生的使用
 * @date: 2021/4/20 11:17
 */
//@RestController
//@RequestMapping("/sentinel")
public class SentenelController {


    private final String RESOURCE_TEST = "test";

    @RequestMapping("/" + RESOURCE_TEST)
    public String test(){

        Entry entry = null;
        try {
             entry = SphU.entry(RESOURCE_TEST);
             //处理业务。。。。
            String msg ="hello sentinel!";
            System.out.println(msg);
            return msg;
        } catch (BlockException e) {
            // 资源访问阻止，被限流或被降级
            //进行相应的处理操作
            System.out.println("block!被限流了。。。。");
            e.printStackTrace();
            return "block!被限流了。。。。";
        }catch (Exception ce){
            // 若需要配置降级规则，需要通过这种方式记录业务异常
            Tracer.traceEntry(ce, entry);
        }finally {
            if(entry != null){
                //释放资源
                entry.exit();
            }
        }
        return null;
    }

    @PostConstruct
    public void init(){

        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        //设置受保护的资源
        rule.setResource(RESOURCE_TEST);
        // 设置流控规则 QPS
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // 设置受保护的资源阈值
        rule.setCount(1);

        rules.add(rule);
        FlowRuleManager.loadRules(rules);
        System.out.println(11111);

    }


}
